package org.god.batis.core;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Author 海晨忆
 * @Des JDBC的事务管理器, 通过Connection对象去处理事务
 * @Date 2025/6/16 15:05
 */
public class JdbcTransaction implements Transaction {
    //数据源
    private DataSource dataSource;
    //是否需要自动提交，true:自动提交，false:不自动提交
    private boolean autoCommit;
    private Connection connection;

    public JdbcTransaction(DataSource dataSource, boolean autoCommit) {
        this.dataSource = dataSource;
        this.autoCommit = autoCommit;
    }

    @Override
    public void commit() {
        try {
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void rollback() {
        try {
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close() {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void openCollection() {
        if (connection == null) {
            try {
                connection = dataSource.getConnection();
                connection.setAutoCommit(autoCommit);
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("请先调用openCollection,开启一个事务连接");
            }
        }
    }

    @Override
    public Connection getConnection() {
        return connection;
    }
}
